package com.lcn.controller;

import com.lcn.api.feign.UsersServiceFeign;
import com.lcn.base.BaseInfoProperties;
import com.lcn.config.MinIOConfig;
import com.lcn.grace.result.GraceJSONResult;
import com.lcn.grace.result.ResponseStatusEnum;
import com.lcn.pojo.vo.UsersVO;
import com.lcn.pojo.vo.VideoMsgVO;
import com.lcn.utils.*;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RequestMapping("/file")
@RestController
public class FileController extends BaseInfoProperties {

    @Resource
    private MinIOConfig minIOConfig;

    @Autowired
    private UsersServiceFeign usersServiceFeign;

    /**
     * 上传头像
     * @param file
     * @param userId
     * @return
     */
    @PostMapping("/uploadFace")
    public GraceJSONResult uploadFace(@RequestParam("file") MultipartFile file, String userId) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
        // 文件名处理: /face/userId/xxx.jpg
        filename = "face" + "/" + userId + "/" + getRandomString(10) + ".jpg";
        // 上传
        MinIOUtils.uploadFile(minIOConfig.getBucketName(), filename, file.getInputStream());
        // 图片访问路径
        String facePath = minIOConfig.getHostname() + "/" + minIOConfig.getBucketName() + "/" + filename;
        // 远程调用-更新用户信息
        GraceJSONResult graceJSONResult = usersServiceFeign.updateFace(userId, facePath);
        Object data = graceJSONResult.getData();
        String json = JsonUtils.objectToJson(data);
        UsersVO usersVO = JsonUtils.jsonToPojo(json, UsersVO.class);
        return GraceJSONResult.ok(usersVO);
    }

    /**
     * 上传朋友圈背景图
     * @param file
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadFriendCircleBg")
    public GraceJSONResult uploadFriendCircleBg(@RequestParam("file") MultipartFile file, String userId) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
        String filename = "friendCircleBg" + "/"  + userId + "/" + FileUtils.dealWithFilename(originalFilename);
        // 上传背景图
        String url = MinIOUtils.uploadFile(minIOConfig.getBucketName(), filename, file.getInputStream(), true);
        // 远程调用-更新用户信息
        GraceJSONResult graceJSONResult = usersServiceFeign.updateFriendCircleBg(userId, url);
        Object data = graceJSONResult.getData();
        String json = JsonUtils.objectToJson(data);
        UsersVO usersVO = JsonUtils.jsonToPojo(json, UsersVO.class);
        return GraceJSONResult.ok(usersVO);
    }

    /**
     * 上传聊天背景图
     * @param file
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadChatBg")
    public GraceJSONResult uploadChatBg(@RequestParam("file") MultipartFile file, String userId) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
        String filename = "chatBg" + "/"  + userId + "/" + FileUtils.dealWithFilename(originalFilename);
        // 上传背景图
        String url = MinIOUtils.uploadFile(minIOConfig.getBucketName(), filename, file.getInputStream(), true);
        // 远程调用-更新用户信息
        GraceJSONResult graceJSONResult = usersServiceFeign.updateChatBg(userId, url);
        Object data = graceJSONResult.getData();
        String json = JsonUtils.objectToJson(data);
        UsersVO usersVO = JsonUtils.jsonToPojo(json, UsersVO.class);
        return GraceJSONResult.ok(usersVO);
    }

    /**
     * 上传朋友圈图片
     * @param file
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadFriendCircleImage")
    public GraceJSONResult uploadFriendCircleImage(@RequestParam("file") MultipartFile file, String userId) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
        String filename = "friendCircleImage" + "/"  + userId + "/" + FileUtils.dealWithFilename(originalFilename);
        // 上传背景图
        String url = MinIOUtils.uploadFile(minIOConfig.getBucketName(), filename, file.getInputStream(), true);
        return GraceJSONResult.ok(url);
    }

    /**
     * 生成二维码
     * @param wechatNum
     * @param userId
     * @return
     */
    @PostMapping("/generateQrCode")
    public String generateQrCode(@RequestParam("wechatNum") String wechatNum, @RequestParam("userId") String userId) throws Exception {
        if (StringUtils.isBlank(wechatNum) || StringUtils.isBlank(userId)) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("wechatNum", wechatNum);
        map.put("userId", userId);
        String json = JsonUtils.objectToJson(map);
        String qrCodePath = QrCodeUtils.generateQRCode(json);
        if (StringUtils.isNotBlank(qrCodePath)) {
            String objectName = "wechatnum/" + userId + "/" + UUID.randomUUID().toString().replace("-", "") + ".jpg";
            String url = MinIOUtils.uploadFile(minIOConfig.getBucketName(), objectName, qrCodePath, true);
            return url;
        }
        return null;
    }

    /**
     * 上传聊天时发送的图片
     *
     * @param file
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadChatPhoto")
    public GraceJSONResult uploadChatPhoto(@RequestParam("file") MultipartFile file, String userId) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
        String filename = "chat" + "/"  + userId + "/photo/" + FileUtils.dealWithFilename(originalFilename);
        // 上传背景图
        String url = MinIOUtils.uploadFile(minIOConfig.getBucketName(), filename, file.getInputStream(), true);
        return GraceJSONResult.ok(url);
    }

    /**
     * 上传聊天时发送的视频
     *
     * @param file
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadChatVideo")
    public GraceJSONResult uploadChatVideo(@RequestParam("file") MultipartFile file, String userId) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
        String filename = "chat" + "/"  + userId + "/video/" + FileUtils.dealWithFilename(originalFilename);
        // 上传背景图
        String url = MinIOUtils.uploadFile(minIOConfig.getBucketName(), filename, file.getInputStream(), true);
        // 视频第一帧
        String coverName = UUID.randomUUID().toString().replace("-", "") + ".jpg";
        String coverPath = JcodecVideoUtil.videoFramesPath
                + File.separator + "video"
                + File.separator + coverName;
        File coverFile = new File(coverPath);
        if (!coverFile.getParentFile().exists()) {
            coverFile.getParentFile().mkdirs();
        }
        JcodecVideoUtil.fetchFrame(file, coverFile);
        // 封面上传
        coverName = "chat/" + userId + "/cover/" + coverName;
        String coverUrl = MinIOUtils.uploadFile(
                minIOConfig.getBucketName(),
                coverName,
                new FileInputStream(coverFile),
                true);
        VideoMsgVO videoMsgVO = new VideoMsgVO();
        videoMsgVO.setCover(coverUrl);
        videoMsgVO.setVideoPath(url);
        return GraceJSONResult.ok(videoMsgVO);
    }

    private String getRandomString(int length) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, length);
        return uuid;
    }

}
